﻿using System;
using System.Linq;
using Actya.Core.Content;
using Actya.Core.Infrastructure;
using Actya.Core.Infrastructure.Events;
using Actya.Core.Security;
using Actya.Core.SiteStructure;
using NUnit.Framework;
using Moq;

namespace Actya.IntegrationTests
{
	[TestFixture]
	public class SiteTests : InMemoryDocumentStoreTestCase
	{
		[Test]
		public void CreateSite()
		{
			// Arrange
			var membershipMock = new Mock<IMembershipService>();
			var eventPublisherMock = new Mock<IEventPublisher>();
			var cmsContextMock = SetupCmsContextMock();
			var siteService = new SiteService(membershipMock.Object, Session, eventPublisherMock.Object, cmsContextMock.Object, null);

			// Act
			var site = siteService.CreateSite("http://localhost/cms", "Test site", "Default theme", "Administrator", "Password");

			// Assert
			Assert.That(site, Is.Not.Null);
			Assert.That(site.Id, Is.Not.Null);
			var siteFromDb = Session.Load<Site>(site.Id);
			Assert.That(siteFromDb, Is.Not.Null);
			Assert.That(siteFromDb.HostUrls.First(), Is.EqualTo("http://localhost/cms"));
		}

		[Test]
		public void CreateSiteShouldCreateHomePage()
		{
			// Arrange
			var membershipMock = new Mock<IMembershipService>();
			var eventPublisherMock = new Mock<IEventPublisher>();
			var cmsContextMock = SetupCmsContextMock();
			var siteService = new SiteService(membershipMock.Object, Session, eventPublisherMock.Object, cmsContextMock.Object, null);

			// Act
			var site = siteService.CreateSite("http://localhost/cms", "Test site", "Default theme", "Administrator", "Password");
			var homePage = Session.Query<Page>().Customize(x => x.WaitForNonStaleResults()).FirstOrDefault();

			// Assert
			Assert.That(site, Is.Not.Null);
			Assert.That(homePage, Is.Not.Null);
			Assert.That(homePage.IsPublished, Is.True);
			Assert.That(homePage.Content, Is.Not.Null);
			Assert.That(homePage.Content, Is.InstanceOf<MultiRegionContent>());
		}

		private Mock<ICmsContext> SetupCmsContextMock()
		{
			var cmsContextMock = new Mock<ICmsContext>();
			var hostMock = new Mock<ICmsHost>();
			cmsContextMock.SetupGet(c => c.Host).Returns(hostMock.Object);

			return cmsContextMock;
		}
	}
}
